//
//  ViewController.swift
//  SwiftToDoList
//
//  Created by 谢志敏 on 2025/7/4.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableview: UITableView!
    
    var items: [TodoItem] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableview.delegate = self
        tableview.dataSource = self
        // Do any additional setup after loading the view.
        loadData()
    }
    
    func loadData () {
        items = TodoStore.shared.loadItems()
        tableview.reloadData()
    }
    
    @IBAction func addButtonTapped(_ sender: Any) {
        let alert = UIAlertController(title: "新增待办", message: nil, preferredStyle: .alert)
        alert.addTextField {
            textfield in textfield.placeholder = "请输入新增待办信息"
        }
        
        let addAction = UIAlertAction(title: "添加", style: .default) { [weak self] _ in
            if let text = alert.textFields?.first?.text, !text.isEmpty {
                let newItem = TodoItem(id: UUID(), title: text, isCompleted: false)
                self?.items.append(newItem)
                TodoStore.shared.saveItems(self?.items ?? [])
                self?.tableview.reloadData()
            }
        }
        alert.addAction(addAction)
        present(alert, animated: true)
    }
    
    // MARK: UITableView delegate methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "TodoCell", for: indexPath)
        let item  = items[indexPath.row]
        cell.textLabel?.text = item.title
        cell.accessoryType = item.isCompleted ? .checkmark : .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        items[indexPath.row].isCompleted.toggle()
        TodoStore.shared.saveItems(items)
        tableView.reloadRows(at: [indexPath], with: .automatic)
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            items.remove(at: indexPath.row)
            TodoStore.shared.saveItems(items)
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }
}
